package vip.mtdp.gateway.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import vip.mtdp.common.exception.AppRTException;
import vip.mtdp.gateway.service.TokenDTO;
import vip.mtdp.gateway.service.TokenService;

import java.util.Date;

/**
 * @author wangguoqing
 * @Description jwt 实现token服务
 * @date 2019/12/5 18:21
 */

@Slf4j
@Service
public class JwtTokenServiceImpl implements TokenService {

    private String secret = "secret";

    private String tokenKey = "token";

    /**
     * 创建token
     *
     * @param tokenDTO
     * @return
     * @throws AppRTException
     */
    @Override
    public String createToken(TokenDTO tokenDTO) throws AppRTException {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            String token = JWT.create().withIssuer(tokenDTO.getIssuer())
                                       .withClaim(tokenKey,tokenDTO.getJsonData())
                                       .withIssuedAt(new Date(tokenDTO.getTimestamp()))
                                       .sign(algorithm);
            return token;
        }catch (Exception e){
            log.error("create token error",e);
            throw new AppRTException(HttpStatus.FORBIDDEN.value(),"create_token_error");
        }
    }

    /**
     *
     * @param token
     * @return 返回json数据的字符串
     * @throws AppRTException
     */
    @Override
    public String decodeToken(String token) throws AppRTException {
        try {
            return JWT.decode(token).getClaim(tokenKey).asString();
        }catch (Exception e){
            throw new AppRTException(HttpStatus.FORBIDDEN.value(),"decode_token_error");
        }
    }
}
